package com.sxt.service.impl;

import com.sxt.entity.Category;
import com.sxt.mapper.CategoryMapper;
import com.sxt.service.CategoryService;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * <p>
 * 产品类目 服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service(timeout = 8000)
@Slf4j
@CacheConfig(cacheNames = "com.sxt.service.impl.CategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

	@Autowired
	private CategoryMapper categoryMapper ;
	
	private static final String INDEX_CATE_DATA = "'all-sub-cate-list'" ;

	@Override
	public List<Category> listParentCategory() {
		log.info("查询父菜单");
		return categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getGrade, 1));
	}

	/**
	 * 负责处理等级的值
	 */
	@CacheEvict(key = INDEX_CATE_DATA)
	public boolean save(Category entity) {
		Assert.notNull(entity,"新增的值不能为空");
		if(entity.getParentId()==null||entity.getParentId()==0L) {
			entity.setParentId(0L);
			entity.setGrade(1); // 父的等级+1
		}else {
			Category parent = getById(entity.getParentId());
			Integer grade = parent.getGrade();
			entity.setGrade(grade+1);
		}
		entity.setRecTime(LocalDateTime.now());
		return super.save(entity);
	}

	@Cacheable(key = INDEX_CATE_DATA)
	public List<Category> getSubCateList() {
		log.info("查询所有的二级菜单");
		return categoryMapper.selectList(new LambdaQueryWrapper<Category>().
				 eq(Category::getGrade, 2).
				 orderByAsc(Category::getSeq)
				 );
	}
}
